package com.yeyks.commonReference.append.mattress.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yeyks.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

@Service
@ConditionalOnBean(MattressApiCallProperties.class)
@Slf4j
public class MattressApiCallService {

    @Autowired
    private MattressApiCallProperties mattressApiCallProperties;


    /**
     * 查询设备在线状态
     *
     * @param imei 机器编号
     * @return
     */
    public boolean getOnlineStatus(String imei) {
        MattressApiCallServiceGetStatusVo onlineStatusBase = getOnlineStatusBase(imei);
        if (onlineStatusBase.getCode().equals(0) && onlineStatusBase.getData().getStatus().equals(1)) {
            return true;
        }
        return false;
    }

    /**
     * 查询设备在线状态
     *
     * @param imei 机器编号
     * @return
     */
    public MattressApiCallServiceGetStatusVo getOnlineStatusBase(String imei) {
        if (StrUtil.isBlank(imei)) {
            throw new ServiceException("床垫机器编号不能为空");
        }
        HttpResponse response = HttpUtil.createPost(mattressApiCallProperties.getQueryStatusUrl())
                .form("user_id", mattressApiCallProperties.getUserId())
                .form("key", mattressApiCallProperties.getKey())
                .form("imei", imei)
                .execute();
        String body = response.body();
        log.info("查询设备在线状态--请求imei:{};返回结果:{}", imei, body);
        MattressApiCallServiceGetStatusVo mattressApiCallServiceGetStatusVo = JSONUtil.toBean(body, MattressApiCallServiceGetStatusVo.class);
        return mattressApiCallServiceGetStatusVo;
    }

    /**
     * 启动继电器机器
     *
     * @param imei 机器编号
     * @param time 时长,秒
     */
    public MattressApiCallServiceBaseVo startUp(String imei, Integer time) {
        if (StrUtil.isBlank(imei)) {
            throw new ServiceException("床垫机器编号不能为空");
        }
        if (null == time) {
            throw new ServiceException("时长不能为空");
        }
        HttpResponse response = HttpUtil.createPost(mattressApiCallProperties.getStartUpUrl())
                .form("user_id", mattressApiCallProperties.getUserId())
                .form("key", mattressApiCallProperties.getKey())
                .form("duration", time)
                .form("imei", imei)
                .execute();
        String body = response.body();
        log.info("启动继电器机器--请求imei:{};启动时长{};返回结果:{}", imei, time, body);
        MattressApiCallServiceBaseVo mattressApiCallServiceBaseVo = JSONUtil.toBean(body, MattressApiCallServiceBaseVo.class);
        return mattressApiCallServiceBaseVo;
    }

}
